package com.dp.proxy.dynamicCGLIB;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author: dupeng
 * @CreateTime: 2025-01-07  10:14
 * @Description: TODO
 */
public class UserServiceProxy implements MethodInterceptor {

    private Object realObject;

    public UserServiceProxy(Object object) {
        this.realObject = object;
    }

    public Object createProxy(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(realObject.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置增强");
        //以下实现都可以，invokeSuper属于cglib，invoke属于jdk
        Object result = methodProxy.invokeSuper(o, objects);
//        Object result = method.invoke(realObject, objects);
        System.out.println("后置增强");
        return result;
    }
}
